package com.tkxgz.elitecourse.codegenerator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * 根据表名生成实体类
 * 
 * @author Soyi Yao
 */
public class EntityUtils {

	public String packageName; // 包名

	public ResultSet rs = null;

	public ResultSetMetaData rsmd = null;

	public String importStr = "";

	private boolean hasImport = false;

	public Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();// 初始化驱动
			String url = "jdbc:mysql://localhost:3306/elite_course?useUnicode=true&characterEncoding=UTF-8";
			String user = "root";
			String password = "root";
			conn = DriverManager.getConnection(url, user, password);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return conn;

	}

	/**
	 * 得到实体类的字符串
	 * 
	 * @param replaceEnable
	 * @return
	 */
	public String createModel(String tableName, boolean replaceEnable) {
		String str = "";
		try {

			// 取得生成路径
			java.net.URL u = new EntityUtils().getClass().getResource("");
			String url = u.toString();// 生成路径
			url = url.replace("codegenerator/", "entity/");
			url = url.replace("file:/", "");

			packageName = url.substring(url.indexOf("classes"));
			url = url.replace("build/classes", "src");
			// 取得包名
			// String packageName = url.substring(url.indexOf("/src/") + 5,
			// url.length());// 包名
			packageName = packageName.replace("classes/", "");
			packageName = packageName.replaceAll("/", ".");
			packageName = packageName.replace(".entity.", ".entity;");

			Connection conn = getConnection();
			Statement stmt = null;
			String className = tableName.replaceAll("^t_", "");
			className = className.substring(0, 1).toUpperCase()
					+ className.substring(1);// 类名

			className = formatClassName(className);

			StringBuffer buffer = new StringBuffer();
			buffer.append("package " + packageName + "\n\n");

			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from " + tableName);
			rsmd = rs.getMetaData();
			List<HashMap<String, String>> colums = new ArrayList<HashMap<String, String>>();
			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				String type = getTypeName(rsmd.getColumnTypeName(i));// 转换数据库和java之间的数据类型
				HashMap<String, String> map = new HashMap<String, String>();
				String columnName = rsmd.getColumnName(i).toLowerCase();
				// 把形如user_name的变成userName
				columnName = formatFieldName(columnName);
				map.put(type, columnName);
				colums.add(map);
			}

			buffer.append(importStr + "\n");

			buffer.append("public class " + className + "{" + "\n\n");
			// 生成类中的属性
			for (HashMap<String, String> map : colums) {
				for (Iterator<Map.Entry<String, String>> it = map.entrySet()
						.iterator(); it.hasNext();) {
					Map.Entry<String, String> entry = it.next();
					String type = entry.getKey();
					String proName = entry.getValue();
					buffer.append("\tprivate ");
					buffer.append(type + " " + proName);
					buffer.append(";");
					buffer.append("\n");
					buffer.append("\n");
				}
			}

			// 生成类中的set get方法
			for (HashMap<String, String> map : colums) {
				for (Iterator<Map.Entry<String, String>> it = map.entrySet()
						.iterator(); it.hasNext();) {
					Map.Entry<String, String> entry = it.next();
					String type = entry.getKey();
					String proName = entry.getValue();
					String proName4Method = proName.substring(0, 1)
							.toUpperCase() + proName.substring(1);// 首字母大写的属性名，用于set
																	// get方法

					buffer.append("\n");
					// get方法
					buffer.append("\tpublic " + type + " get" + proName4Method
							+ "(){\n");
					buffer.append("\t\treturn " + proName + ";\n");
					buffer.append("\t}\n");

					buffer.append("\n");

					// set
					buffer.append("\tpublic void set" + proName4Method + "("
							+ type + " " + proName + "){\n");
					buffer.append("\t\tthis." + proName + " = " + proName
							+ ";\n");
					buffer.append("\t}\n");
				}
			}

			File f = new File(url);
			boolean fileExist = f.exists();
			if (!fileExist || (fileExist && replaceEnable)) {

				if (!fileExist) {
					f.mkdir();
				}

				buffer.append("}");
				str = buffer.toString();

				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(url + className + ".java")));
				bw.write(str);
				bw.flush();
				bw.close();
			} else {
				System.out.println("数据表" + tableName + "设置了不允许覆盖");
			}

		} catch (Exception e) {

			e.printStackTrace();
		}
		return str;
	}

	/**
	 * @author Soyi Yao
	 * @since 2013-3-9 下午3:50:34
	 * @param className
	 * @return
	 */
	private String formatClassName(String className) {
		String[] str = className.toLowerCase().split("_");
		String result = StringUtils.capitalize(str[0]);
		for (int i = 1; i < str.length; i++) {
			str[i] = StringUtils.capitalize(str[i]);
			result += str[i];
		}

		return result;
	}

	/**
	 * 将形如"t_user_name"的变成"tUserName"
	 * 
	 * @author Soyi Yao
	 * @since 2013-3-9 下午2:59:58
	 * @param columnName
	 * @return
	 */
	private String formatFieldName(String columnName) {
		String[] str = columnName.toLowerCase().split("_");
		String result = str[0];
		for (int i = 1; i < str.length; i++) {
			str[i] = StringUtils.capitalize(str[i]);
			result += str[i];
		}

		return result;
	}

	/**
	 * 用于转换数据库和java之间的数据类型
	 * 
	 * @param typeName
	 * @return
	 */
	public String getTypeName(String typeName) {
		String typeStr = "";

		if (typeName.toLowerCase().trim().equalsIgnoreCase("varchar")) {
			typeStr = "String";
		} else if (typeName.toLowerCase().trim().equalsIgnoreCase("int")) {
			typeStr = "Integer";
		} else if (typeName.toLowerCase().trim().equalsIgnoreCase("datetime")) {
			typeStr = "Date";
			if (!hasImport) {
				importStr += "import java.util.Date;\n";
				hasImport = true;
			}
		} else if (typeName.toLowerCase().trim().equalsIgnoreCase("date")) {
			typeStr = "Date";
			if (!hasImport) {
				importStr += "import java.util.Date;\n";
				hasImport = true;
			}
		} else {
			typeStr = "Object";
			System.err.println("没有找到正确的类型:" + typeStr);
		}
		return typeStr;

	}

	/**
	 * 生成update.jsp页面中的替换字符串
	 * 
	 * @return
	 */

	/**
	 * 生成list.jsp页面中的替换字符串
	 * 
	 * @return
	 */

	public void main(String arg[]) {

	}
}
